package common

import (
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
)

// Response 统一响应结构
type Response struct {
	Code    int         `json:"code"`    // 响应码
	Message string      `json:"message"` // 响应消息
	Data    interface{} `json:"data"`    // 响应数据
}

// Success 成功响应
func Success(c *gin.Context, data interface{}) {
	c.JSON(http.StatusOK, Response{
		Code:    0,
		Message: "success",
		Data:    data,
	})
}

// Error 错误响应，接受error或string类型
func Error(c *gin.Context, message interface{}) {
	var msg string
	switch v := message.(type) {
	case error:
		msg = v.Error()
	case string:
		msg = v
	default:
		msg = "未知错误"
	}

	c.JSON(http.StatusOK, Response{
		Code:    1,
		Message: msg,
		Data:    nil,
	})
}

// ErrorWithMsg 带错误信息的错误响应，同时接受error和自定义错误消息
func ErrorWithMsg(c *gin.Context, err error, message string) {
	c.JSON(http.StatusOK, Response{
		Code:    1,
		Message: message,
		Data:    nil,
	})
}

// BadRequest 错误请求响应
func BadRequest(c *gin.Context, message string) {
	c.JSON(http.StatusBadRequest, Response{
		Code:    400,
		Message: message,
		Data:    nil,
	})
}

// NotFound 资源不存在响应
func NotFound(c *gin.Context, message string) {
	c.JSON(http.StatusNotFound, Response{
		Code:    404,
		Message: message,
		Data:    nil,
	})
}

// GetIDParam 获取路径参数ID
func GetIDParam(c *gin.Context) uint {
	id, err := strconv.ParseUint(c.Param("id"), 10, 32)
	if err != nil {
		Error(c, err.Error())
		return 0
	}
	return uint(id)
}

// GetUserID 从上下文获取用户ID
func GetUserID(c *gin.Context) uint {
	userID, exists := c.Get("userID")
	if !exists {
		return 0
	}
	return userID.(uint)
}

// GetUsername 从上下文获取用户名
func GetUsername(c *gin.Context) string {
	username, exists := c.Get("username")
	if !exists {
		return ""
	}
	return username.(string)
}

// GetRoleID 从上下文获取角色ID
func GetRoleID(c *gin.Context) uint {
	roleID, exists := c.Get("roleID")
	if !exists {
		return 0
	}
	return roleID.(uint)
}
